/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

 //顺序合并
// class Solution {
// public:
//     ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
//         ListNode* newHead = new ListNode;
//         ListNode* curA = list1;
//         ListNode* curB = list2;
//         ListNode* cur = newHead;

//         while (curA && curB)
//         {
//             if (curA->val <= curB->val)
//             {
//                 cur->next = curA;
//                 curA = curA->next;
//             }
//             else
//             {
//                 cur->next = curB;
//                 curB = curB->next;
//             }
//             cur = cur->next;
//         }

//         cur->next = curA ? curA : curB;
            
//         ListNode* head = newHead->next;
//         delete newHead;
//         return head;
//     }
//     ListNode* mergeKLists(vector<ListNode*>& lists) {
//         if (lists.size() == 0)
//             return nullptr;
//         //ListNode* dummyHead = new ListNode;
//         ListNode* head = nullptr;
//         for (int i = 0; i < lists.size(); i++)
//         {
//             head = mergeTwoLists(head, lists[i]);
//         }
//         return head;

//     }
// };

//归并
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        ListNode* newHead = new ListNode;
        ListNode* curA = list1;
        ListNode* curB = list2;
        ListNode* cur = newHead;

        while (curA && curB)
        {
            if (curA->val <= curB->val)
            {
                cur->next = curA;
                curA = curA->next;
            }
            else
            {
                cur->next = curB;
                curB = curB->next;
            }
            cur = cur->next;
        }

        cur->next = curA ? curA : curB;
            
        ListNode* head = newHead->next;
        delete newHead;
        return head;
    }
    ListNode* mergeKLists(vector<ListNode*>& lists, int left, int right)
    {
        if (left >= right)
            return left >= lists.size() ? nullptr : lists[left];
            
        int mid = (right - left) / 2 + left;
        return mergeTwoLists(mergeKLists(lists, left, mid), mergeKLists(lists, mid + 1, right));
    }
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if (lists.size() == 0)
            return nullptr;
        
        return mergeKLists(lists, 0, lists.size());
    }
};